<!--
 * @FileDescription: 创建阶段检查页面
 * @Author: 夏世龙
 * @Date: 2021-9-9
 * @LastEditors: 夏世龙
 * @LastEditTime: 2021-10-19
 -->
<template>
  <div>
    <p id="Title">新建阶段检查</p>
    <div id="phaseForm">
      <div>
        <el-form ref="phaseForm" :model="phaseForm" label-width="140px" >
          <el-row>
            <el-col :span="12">
              <el-form-item
              label="阶段检查名称"
              prop="phaseName"
              :rules="{ required: true, message: '请输入阶段检查名称', trigger: 'blur' }"
              >
                <el-input v-model="phaseForm.phaseName" style="width:445px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="教师申报时间"
               :prop="phaseTeacher"
               :rules="{ required: true,message: '请补全教师申报时间！', trigger: 'blur'}"
               >
              	<DateTimeRange :before.sync="date" :start.sync="phaseForm.phaseTeacherStart"
              		:end.sync="phaseForm.phaseTeacherEnd" :last.sync="phaseForm.phaseDepartmentStart">
              	</DateTimeRange>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="学院评审时间"
               :prop="phaseDepartment"
               :rules="{ required: true,message: '请补全学院评审时间！', trigger: 'blur'}"
               >
              	<DateTimeRange :before.sync="phaseForm.phaseTeacherEnd" :start.sync="phaseForm.phaseDepartmentStart"
              		:end.sync="phaseForm.phaseDepartmentEnd" :last.sync="phaseForm.phaseSchoolFirstStart">
              	</DateTimeRange>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="学校评审时间"
               :prop="phaseSchool"
               :rules="{ required: true,message: '请补全学校评审时间！', trigger: 'blur'}"
               >
              	<DateTimeRange :before.sync="phaseForm.phaseDepartmentEnd" :start.sync="phaseForm.phaseSchoolFirstStart"
              		:end.sync="phaseForm.phaseSchoolFirstEnd" :last.sync="last">
              	</DateTimeRange>
              </el-form-item>
            </el-col>
          </el-row>
              <el-form-item
              label="阶段检查申报材料"
              prop="path"
              :rules="{ required: true, message: '请上传阶段检查申报材料', trigger: 'blur' }"
              style="width: 500px;"
              >
                <el-upload
                  class="upload-demo"
                  :action="baseUrl+'/file/fileUpload'"
                  :headers="headerObj"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-success="upLoadSuccess"
                  accept=".zip,.rar"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :file-list="fileList">
                  <el-button size="small" type="primary">上传压缩包</el-button>
                </el-upload>
              </el-form-item>
        </el-form>
      </div>
        <el-row >
          <el-col :span="11">
            <p class="SecondTitle">未选批次</p>
          </el-col>
          <el-col :span="2">
            <p></p>
          </el-col>
          <el-col :span="11">
            <p class="SecondTitle">已选批次</p>
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex">
          <el-col :span="11">
            <el-table
               height="500px"
                v-loading="leftLoading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                ref="mulLeftSelection"
                :row-key="getRowKey"
                :data="showTable"
                tooltip-effect="dark"
                style="width: 100%"
                :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
                :cell-style="{'text-align':'center'}"
                @selection-change="handleSelectionChange">
                <el-table-column
                  type="selection"
                  :reserve-selection="true"
                  width="55">
                </el-table-column>
                <el-table-column
                  label="批次名称">
                  <template slot-scope="scope">{{ scope.row.batchName }}</template>
                </el-table-column>
                <el-table-column
                  prop="levelName"
                  label="等级">
                </el-table-column>
                <el-table-column
                  prop="company"
                  label="所属部门"
                  show-overflow-tooltip>
                </el-table-column>
              </el-table>
              <div class="resource-page">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :page-sizes="[5,10, 15]"
                  :page-size="pagesize"
                  :pager-count="7"
                  layout=" prev, pager, next,sizes, jumper"
                  :total="unSelectedBatchTable.length"
                >
                </el-pagination>
              </div>
          </el-col>
          <el-col :span="2" style="text-align:center;">
            <div style="position: relative;top:50%;transform:translateY(-50%);">
              <div>
                <el-button
                    @click="removeLeftToRight"
                    type="primary"
                    :disabled="!mulLeftSelection.length"
                    icon="el-icon-arrow-right"
                    circle
                ></el-button>
              </div>
              <el-button
                  @click="removeRightToLeft"
                  type="primary"
                  :disabled="!mulRightSelection.length"
                  icon="el-icon-arrow-left"
                  circle
                  style="margin-left: 0;margin-top: 10px;"
              ></el-button>
              </div>
          </el-col>
          <el-col :span="11">
              <el-table
                  height="500px"
                  ref="mulRightSelection"
                  :data="showRightTable"
                  tooltip-effect="dark"
                  style="width: 100%"
                  :row-key="getRowKey"
                  :cell-style="{'text-align':'center'}"
                  :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
                  @selection-change="handleSelectionChangeRight">
                  <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    width="55">
                  </el-table-column>
                  <el-table-column
                    label="批次名称">
                    <template slot-scope="scope">{{ scope.row.batchName }}</template>
                  </el-table-column>
                  <el-table-column
                    prop="levelName"
                    label="等级">
                  </el-table-column>
                  <el-table-column
                    prop="company"
                    label="所属部门"
                    show-overflow-tooltip>
                  </el-table-column>
                </el-table>
                <div class="resource-page">
                  <el-pagination
                    @size-change="handleRightSizeChange"
                    @current-change="handleRightCurrentChange"
                    :page-sizes="[5,10,15]"
                    :page-size="rightPagesize"
                    :pager-count="7"
                    layout=" prev, pager, next,sizes, jumper"
                    :total="selectedBatchTable.length"
                  >
                  </el-pagination>
                </div>
          </el-col>
        </el-row>
      </div>

    <p style="text-align: center;">
      <el-button
      type="primary"
       @click="saveButton()"
       >保存</el-button>
    </p>
  </div>

</template>

<script>
   import DateTimeRange from "@/components/DateTimeRange";
   export default {
     created() {
       console.log(this.baseUrl)
       this.getAllBatchAxios()
     }
     ,
     components: {
     	DateTimeRange
     },
     computed:{
       phaseSchool(){
          if(this.phaseForm.phaseSchoolFirstStart==''){
            return 'phaseSchoolFirstStart'
          }else{
            return 'phaseSchoolFirstEnd'
          }
       },
       phaseDepartment(){
          if(this.phaseForm.phaseDepartmentStart==''){
            return 'phaseDepartmentStart'
          }else{
            return 'phaseDepartmentEnd'
          }
       }
       ,
       phaseTeacher(){
         if(this.phaseForm.phaseTeacherStart==''){
           return 'phaseTeacherStart'
         }else{
           return 'phaseTeacherEnd'
         }
       },
      //showTable计算属性通过slice方法计算表格当前应显示的数据
      showTable() {
        return this.unSelectedBatchTable.slice(
          (this.currentPage - 1) * this.pagesize,
          this.currentPage * this.pagesize
        );
      },
      showRightTable() {
        return this.selectedBatchTable.slice(
          (this.rightCurrentPage - 1) * this.rightPagesize,
          this.rightCurrentPage * this.rightPagesize
        );
      },
     },
      data() {
        return {
          baseUrl:process.env.Base_API,
          allBatch:[],
          //上传方法调用请求头部
          headerObj: {
          	token: this.$store.state.token,
          	tokenHead: this.$store.state.tokenHead,
          	jsession_id: this.$store.state.jsession_id
          },
          leftLoading:true,
          last: "",
          date: Date.now() - 24 * 60 * 60 * 1000,
          phaseForm: {
            //阶段检查名称
            phaseName: '',
            //上传材料模板地址
            path:'',
            //材料模板名
            pathName:'',
            //教师申报开始时间(yyyy-MM-dd)
            phaseTeacherStart:'',
            //教师申报结束时间(yyyy-MM-dd)
            phaseTeacherEnd:'',
            //学院检查开始时间(yyyy-MM-dd)
            phaseDepartmentStart:'',
            //学院检查结束时间(yyyy-MM-dd)
            phaseDepartmentEnd:'',
            //学校检查一审结束时间(yyyy-MM-dd)
            phaseSchoolFirstStart:'',
            //学校检查一审结束时间(yyyy-MM-dd)
            phaseSchoolFirstEnd:''
          },
          fileList: [],
          //未选批次
          unSelectedBatchTable:[],
          copyUnSelectedBatchTable:[],
          mulLeftSelection: [],
          //已选批次
          selectedBatchTable:[],
          mulRightSelection: [],
          //左侧页面显示个数
          pagesize: 5,
          //左面显示当前页数
          currentPage: 1,
          //右侧页面显示个数
          rightPagesize: 5,
          //右面显示当前页数
          rightCurrentPage: 1,
          filterDataShow: [], //储存符合条件的数据-
          }
      },
      methods:{
        //保存按钮
        saveButton(){
          this.$refs["phaseForm"].validate((valid) => {
              if (valid) {
                if(this.selectedBatchTable.length<=0){
                  this.$message({
                    message:"请选择批次！",
                    type:"warning",
                    offset: screen.height / 2 - 200,
                    duration:2000,
                    center:true
                  })
                  return false;
                }
                this.SubmitAxios()
              } else {
                this.$message({
                  message:"请补全必填信息！",
                  center:true,
                  type:"warning",
                  offset: screen.height / 2 - 200,
                  duration:2000
                })
                return false;
              }
            });
        },
        //提交接口
        SubmitAxios(){
          this.$api.phase.creatPhase({
            path:this.phaseForm.path,
            pathName:this.phaseForm.pathName,
            phaseDepartmentEnd:this.phaseForm.phaseDepartmentEnd,
            phaseDepartmentStart:this.phaseForm.phaseDepartmentStart,
            phaseName:this.phaseForm.phaseName,
            phaseSchoolFirstEnd:this.phaseForm.phaseSchoolFirstEnd,
            phaseSchoolFirstStart:this.phaseForm.phaseSchoolFirstStart,
            phaseTeacherEnd:this.phaseForm.phaseTeacherEnd,
            phaseTeacherStart:this.phaseForm.phaseTeacherStart,
            status:5,
            type:2
          }).then((response)=>{
            console.log(response)
            var phaseId = response.data.data.phaseId
            var batchPhaseInfo = []
            var itemBpinfo = {phaseId:'',batchId:'',batchName:'',levelName:'',company:'',phaseSecondEnd:''}
            this.selectedBatchTable.forEach(item => {
              itemBpinfo.batchId=item.batchId
              //更改批次状态为 5 院级阶段检查
              this.$api.batch.updateBatchStatus({batchId:item.batchId,status:5}).then((res)=>{
              })
              batchPhaseInfo.push(JSON.parse(JSON.stringify(itemBpinfo)))
            })
            console.log(batchPhaseInfo)
            this.$api.phase.insertBatchPhase({
              phaseId:phaseId,
              batchIdInfo:JSON.stringify(batchPhaseInfo)
            }).then((response)=>{
              console.log(response)
              this.$message({
                message:'结项检查创建成功!',
                type:'success',
                center:true,
                offset:screen.height / 2 - 200
              })
              setTimeout(()=>{
                this.jumpMetahsse()
              },0)
            })
          })
        },
        //跳转到中期管理页面
        jumpMetahsse(){
          this.$router.push({path:'/metahsse'})
        },
        //文件上传成功后的钩子函数
        upLoadSuccess(response){
          console.log(response)
          this.$refs['phaseForm'].clearValidate('path');
          var tempPathName={},tempFileList=[]
          this.phaseForm.path=response.data[0].filePath
          this.phaseForm.pathName=response.data[0].fileName
          this.$set(tempPathName,'name',response.data[0].fileName)
          tempFileList.push(tempPathName)
          this.tempFileList=tempFileList
        },
        //移动左侧表格内容到右方
        removeLeftToRight(){
            setTimeout(() => {
              this.$refs["mulLeftSelection"].clearSelection();
            }, 0);
            for(let i = 0 ; i < this.unSelectedBatchTable.length ; i++){
              for(let j = 0; j<this.mulLeftSelection.length;j++){
                if(this.mulLeftSelection[j].batchId==this.unSelectedBatchTable[i].batchId){
                  this.unSelectedBatchTable.splice(i,1)
                  const totalPage = Math.ceil((this.unSelectedBatchTable.length ) / this.pagesize)
                  this.currentPage = this.currentPage > totalPage ? totalPage : this.currentPage
                  this.currentPage = this.currentPage < 1 ? 1 : this.currentPage
                  this.selectedBatchTable.push(this.mulLeftSelection[j])
                }
              }
            }
        },
        //右边表格内容到左边
        removeRightToLeft(){
          setTimeout(() => {
            this.$refs["mulRightSelection"].clearSelection();
          }, 0);
          for(let i = 0 ; i < this.selectedBatchTable.length ; i++){
            for(let j = 0; j<this.mulRightSelection.length;j++){
              if(this.mulRightSelection[j].batchId==this.selectedBatchTable[i].batchId){
                this.selectedBatchTable.splice(i,1)
                let totalPage = Math.ceil((this.selectedBatchTable.length - 1) / this.rightPagesize)
                this.rightCurrentPage = this.rightCurrentPage > totalPage ? totalPage : this.rightCurrentPage
                this.rightCurrentPage = this.rightCurrentPage < 1 ? 1 : this.rightCurrentPage
                this.unSelectedBatchTable.push(this.mulRightSelection[j])
              }
            }
          }
        },
        getRowKey(row) {
          //得到当前行的key值用于保留分页前的数据
              return row.batchId
        },
        //左侧当前页面个数改变方法
        handleSizeChange(psize) {
          this.pagesize = psize;
        },
        //左侧当前分页选中页
        handleCurrentChange(currentPage) {
          this.currentPage = currentPage;
        },
        handleRightSizeChange(psize) {
          this.rightPagesize = psize;
        },
        //左侧当前分页选中页
        handleRightCurrentChange(currentPage) {
          this.rightCurrentPage = currentPage;
        },
        //获得所有批次信息,并且赋值给左侧表格unSelectedBatchTable
        getAllBatchAxios(){
          this.$api.batch.getAllBatch().then((response)=>{
            console.log(response)
            this.allBatch=response.data.data.filter(item => item.status==4)
            this.unSelectedBatchTable=JSON.parse(JSON.stringify(this.allBatch))
            this.leftLoading=false
          })
        },
        handleSelectionChange(val) {
          this.mulLeftSelection = val;
        },
        handleSelectionChangeRight(val) {
          this.mulRightSelection = val;
        },
        onSubmit(){
          console.log('submit!');
        },
        handleRemove(file, fileList) {
          var fileNames=this.phaseForm.path.split('/')
          this.$api.file.fileDelete({
            fileNames:fileNames[fileNames.length-1]
          }).then((response)=>{
            console.log(response)
            this.phaseForm.path=''
            this.phaseForm.pathName=''
            this.fileList=[]
            console.log(file, fileList);
          })
        },
        handlePreview(file) {
          console.log(file);
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
          return this.$confirm(`确定移除 ${ file.name }？`);
        }
      }
    }
</script>

<style scoped>
  #phaseForm{
      margin-top: 50px;
      width:1400px;
      position: relative;
      left: 50%;
      transform: translateX(-50%);
  }
  #Title{
    /* margin: 0 0 10px 0;
    font-weight:300;
    text-align: center;
    font-size: 30px; */
    font-weight:300;
    text-align: center;
    font-size: 40px;
  }
  .SecondTitle{
    text-align: center;
    font-size:25px;
    margin: 0 0 10px 0;
  }
</style>
